﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Diploma.Models;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Web;

namespace DiplomaWeb.Controllers
{
    [Authorize(Roles = "SystemManager")]
    public class SubOrderPracticeController : MasterController
    {
        public SubOrderPracticeController(DataManager dataManager)
            : base(dataManager)
        {
        }

        #region Management SubOrderPractice

        public ActionResult Room(Guid subOrderId)
        {
            SubOrderPractice model = DataManager.SubOrderPracticeRepository.Get(subOrderId);
            ViewData.Model = model;
            return View("~/Views/SystemManagers/SubOrderPractice/OrderRoom.aspx");
        }

        #endregion

        #region Ajax Management SubOrderPractice

        /// <summary>
        /// Создание под приказа
        /// </summary>
        /// <param name="students">Список студентов</param>
        /// <param name="orderId">Основной Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreateSubOrder(string students, Guid orderId)
        {
            if (String.IsNullOrEmpty(students))
                return Json(new { status = false, message = "Error string" });

            string[] array = students.Split(';');
            IEnumerable<Guid> studentIds = from s in array select new Guid(s);
            OrderPractice order = DataManager.OrderPracticeRepository.GetOrder(orderId);
            const string textTemplate = "У відповідності до навчального плану нижчевказаних студентів 5-го курсу денної форми навчання, факультету <скорочена назва факультету> спеціальності <повна назва спеціальності>, направити з <дата у форматі ДД.ММ.РР> по <дата у форматі ДД.ММ.РР> на дослідницьку практику, закріпити за ними теми магістерських робіт, призначити керівників робіт та керівників дослідницької практики";
            const string dateAndOrderNumber = "_____________________№_______________________";
            var subOrder = new SubOrderPractice
                               {
                                   Id = Guid.NewGuid(),
                                   OrderPractice = order,
                                   CreateDate = DateTime.Now,
                                   UpdateDate = DateTime.Now,
                                   OrderStatu = DataManager.OrderStatusRepository.GetStatus(0),
                                   Text = textTemplate,
                                   DateAndOrderNumber = dateAndOrderNumber
                               };

            IEnumerable<SaveStateOrderPractice> list = from b in studentIds
                                                       select DataManager.OrderPracticeRepository.GetStudentFromSSOP(b);
            foreach (SaveStateOrderPractice saveStateOrderPractice in list)
            {
                subOrder.SaveStateOrderPractices.Add(saveStateOrderPractice);
            }

            DataManager.OrderPracticeRepository.SaveChanges();

            return Json(new { status = true });
        }

        /// <summary>
        /// Загрузка списка студентов
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult StudentList(Guid orderId)
        {
            ViewData.Model = DataManager.SubOrderPracticeRepository.Get(orderId);
            return View("~/Views/SystemManagers/SubOrderPractice/StudentList.ascx");
        }

        /// <summary>
        /// Загрузка информиции о под приказе
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetInfo(Guid orderId)
        {
            SubOrderPractice order = DataManager.SubOrderPracticeRepository.Get(orderId);
            ViewData.Model = order;
            return View("~/Views/SystemManagers/SubOrderPractice/OrderInfo.cshtml");
        }

        /// <summary>
        /// Форма редактирования информации
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetEditForm(Guid orderId)
        {
            SubOrderPractice order = DataManager.SubOrderPracticeRepository.Get(orderId);
            ViewData.Model = order;
            return View("~/Views/SystemManagers/SubOrderPractice/EditOrderInfo.cshtml");
        }

        /// <summary>
        /// Сохранение информации
        /// </summary>
        /// <param name="orderId">Под приказ</param>
        /// <param name="title">Заголовок</param>
        /// <param name="text">Текст</param>
        /// <param name="bookName">Название книги</param>
        /// <param name="dateAndOrderNumber"> </param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveInfo(Guid orderId, string title, string text, string bookName, string dateAndOrderNumber)
        {
            try
            {
                SubOrderPractice model = DataManager.SubOrderPracticeRepository.Get(orderId);

                model.Title = title;
                model.Text = text;
                model.BookName = bookName;
                model.DateAndOrderNumber = dateAndOrderNumber;

                DataManager.SubOrderPracticeRepository.SaveChanges();

                return Json(true);
            }
            catch (Exception)
            {
                return Json(false);
            }
        }

        /// <summary>
        /// Получение отображения статуса
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetStatus(Guid orderId)
        {
            SubOrderPractice currentStatus = DataManager.SubOrderPracticeRepository.Get(orderId);
            IEnumerable<OrderStatu> statuses = DataManager.OrderStatusRepository.GetAll();
            IEnumerable<SelectListItem> model;
            if (currentStatus.OrderStatu.Value == 0)
            {
                model = from b in statuses
                        where b.Value >= currentStatus.OrderStatu.Value
                        orderby b.Value
                        select new SelectListItem
                                   {
                                       Text = b.DisplayName,
                                       Value = b.Id.ToString(),
                                       Selected = b.Id == currentStatus.OrderStatu.Id
                                   };
            }
            else
            {
                model = from b in statuses
                        where b.Value >= currentStatus.OrderStatu.Value
                        where b.Value != 3
                        orderby b.Value
                        select new SelectListItem
                                   {
                                       Text = b.DisplayName,
                                       Value = b.Id.ToString(),
                                       Selected = b.Id == currentStatus.OrderStatu.Id
                                   };
            }
            ViewData.Model = model;
            return View("~/Views/SystemManagers/SubOrderPractice/OrderStatus.ascx");
        }

        /// <summary>
        /// Сохранение статуса приказа
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <param name="statusId">Статус</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveStatus(Guid orderId, Guid statusId)
        {
            SubOrderPractice order = DataManager.SubOrderPracticeRepository.Get(orderId);
            OrderStatu status = DataManager.OrderStatusRepository.GetStatus(statusId);
            order.OrderStatu = status;
            DataManager.SubOrderPracticeRepository.SaveChanges();
            return Json(true);
        }

        /// <summary>
        /// Отображение формы загрузки
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadFilesView(Guid orderId)
        {
            SubOrderPractice model = DataManager.SubOrderPracticeRepository.Get(orderId);
            ViewData.Model = model;
            return View("~/Views/SystemManagers/SubOrderPractice/UploadFiles.ascx");
        }

        /// <summary>
        /// Загрузка и прикрипление файла к приказу
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadFile(Guid orderId)
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i] != null)
                {
                    HttpPostedFileBase file = Request.Files[i];
                    //Проверка на размер файла
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileName = String.Format("{0}_{1}", DateTime.Now.Ticks, file.FileName);
                        var path = String.Format("{0}{1}", Configuration.Settings.OrderPracticeContentPath, fileName);

                        if(!Directory.Exists(Configuration.Settings.OrderPracticeContentPath))
                        {
                            Directory.CreateDirectory(Configuration.Settings.OrderPracticeContentPath);
                        }

                        SubOrderPractice order = DataManager.SubOrderPracticeRepository.Get(orderId);
                        var document = new VerifyDocument
                                           {
                                               Id = Guid.NewGuid(),
                                               DocumentURL = path
                                           };
                        order.VerifyDocuments.Add(document);

                        file.SaveAs(path);
                        DataManager.SubOrderPracticeRepository.SaveChanges();
                    }
                }
            }
            return RedirectToRoute("Default",
                                   new { controller = "SubOrderPractice", action = "Room", subOrderId = orderId });
        }

        [HttpPost]
        public ActionResult Content(Guid orderId, Guid documentId, string action)
        {
            SubOrderPractice order = DataManager.SubOrderPracticeRepository.Get(orderId);
            VerifyDocument file = order.VerifyDocuments.First(r => r.Id == documentId);
            var fileInfo = new FileInfo(file.DocumentURL);
            switch (action)
            {
                case "delete":
                    order.VerifyDocuments.Remove(file);
                    DataManager.SubOrderPracticeRepository.SaveChanges();
                    if (fileInfo.Exists)
                    {
                        fileInfo.Delete();
                    }
                    break;
                case "download":
                    if (fileInfo.Exists)
                    {
                        return File(fileInfo.FullName, "image/jpeg", fileInfo.Name);
                    }
                    break;
                default:
                    throw new Exception();
            }
            return RedirectToRoute("Default",
                                   new { controller = "SubOrderPractice", action = "Room", subOrderId = orderId });
        }

        #endregion

        #region Excel

        /// <summary>
        /// Создание Excel файла
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GenerateExcel(Guid orderId)
        {
            string pathToFile = Configuration.Settings.OrderPracticePath + orderId + ".xls";
            var fileInfo = new FileInfo(pathToFile);
            if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
            {
                Directory.CreateDirectory(fileInfo.Directory.FullName);
            }

            SubOrderPractice order = DataManager.SubOrderPracticeRepository.Get(orderId);
            PracticeTemplate(fileInfo, order);

            var title = !String.IsNullOrWhiteSpace(order.Title) ? order.Title : "OrderName";
            return base.File(fileInfo.FullName, "application/ms-excel", title + ".xls");
        }

        public ActionResult ExcelViewPart(Guid orderId)
        {
            SubOrderPractice order = DataManager.SubOrderPracticeRepository.Get(orderId);
            ViewData.Model = order;
            return View("~/Views/SystemManagers/SubOrderPractice/ExcelView.ascx");
        }

        #endregion

        #region Private 

        private static void PracticeTemplate(FileInfo fileInfo, SubOrderPractice order)
        {
            if (!IsNewFile(fileInfo, order.OrderStatu.Value))
                return;

            using (var p = new ExcelPackage())
            {
                var bookName = !String.IsNullOrWhiteSpace(order.BookName) ? order.BookName : "Book 1";
                ExcelWorksheet ws = p.Workbook.Worksheets.Add(bookName);
                int rowId = 11;
                int i = 0;

                ws.Column(1).Width = 5.0;
                ws.Column(2).Width = 30.29;
                ws.Column(3).Width = 12;
                ws.Column(4).Width = 29.14;
                ws.Column(5).Width = 20;
                ws.Column(6).Width = 34;
                ws.Column(7).Width = 18.71;
                ws.Column(8).Width = 17.29;

                ws.Row(1).Height = 22.5;
                ws.Row(2).Height = 34.5;
                ws.Row(3).Height = 18.75;
                ws.Row(4).Height = 39;
                ws.Row(5).Height = 20.25;
                ws.Row(6).Height = 33.75;
                ws.Row(7).Height = 15;
                ws.Row(8).Height = 78;

                ws.Cells["D1,D2,D3,D4,G5,A5,A6,A8,A11,B11,C11,D11,E11,F11,G11,H11,J11"].Style.Font.Name =
                    "Times New Roman";

                ws.Cells["D2,D3,D4"].Style.Font.Size = 20;
                ws.Cells["A5,A6,A8,A11,D1"].Style.Font.Size = 16;
                ws.Cells["B11,C11,D11,E11,F11,G11,H11,J11"].Style.Font.Size = 12;
                //Текст жирным
                ws.Cells["D1,D2,D3,D4"].Style.Font.Bold = true;
                //Перенос текста
                ws.Cells["A8,A11,B11,C11,D11,E11,F11,G11,H11,J11"].Style.WrapText = true;
                //Вертикальное выравнивание
                ws.Cells["C1,B2,D3,A5,G5,A8,A11,B11,C11,D11,E11,F11,G11,H11,J11"].Style.VerticalAlignment =
                    ExcelVerticalAlignment.Center;
                ws.Cells["A6"].Style.VerticalAlignment = ExcelVerticalAlignment.Bottom;
                //Горизонтальное выравнивание
                ws.Cells["D1,D2,D3,D4,A5,A11,B11,C11,D11,E11,F11,G11,H11,J11"].Style.HorizontalAlignment =
                    ExcelHorizontalAlignment.Center;
                ws.Cells["A6,A8"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;


                ws.Cells["D1:F1"].Merge = true;
                ws.Cells["D1"].Value = "Міністерство освіти і науки України";

                ws.Cells["D2:F2"].Merge = true;
                ws.Cells["D2"].Value = "ХАРКIВСЬКИЙ НАЦІОНАЛЬНИЙ";

                ws.Cells["D3:F3"].Merge = true;
                ws.Cells["D3"].Value = "УНIВЕРСИТЕТ РАДIОЕЛЕКТРОНIКИ";

                ws.Cells["D4:F4"].Merge = true;
                ws.Cells["D4"].Value = "НАКАЗ";

                ws.Cells["A5:D5"].Merge = true;
                //ws.Cells["A5"].Value = "_____________________№_______________________";
                ws.Cells["A5"].Value = order.DateAndOrderNumber;

                ws.Cells["A6:D6"].Merge = true;
                ws.Cells["A6"].Value = "Про направлення на дослідницьку практику";

                ws.Cells["A8:H8"].Merge = true;
                ws.Cells["A8"].Value = order.Text;

                //Заполнение тела приказа с студентами
                ws.Cells["A11"].Value = "№ п/п";

                ws.Cells["B11"].Value = "Прізвище, ім'я та по батькові студента";

                ws.Cells["C11"].Value = "Учбова група";

                ws.Cells["D11"].Value = "Місце проходження практики";

                ws.Cells["E11"].Value = "Керівник практики   (посада. ПІБ)";

                ws.Cells["F11"].Value = "Тема дипломного проекту";

                ws.Cells["G11"].Value = "Керівник дипломного проекту (посада. ПІБ)";

                ws.Cells["H11"].Value = "Примітки";

                if (order.SaveStateOrderPractices == null)
                    return;

                foreach (SaveStateOrderPractice item in order.SaveStateOrderPractices)
                {
                    rowId++;
                    i++;

                    ws.Cells["A" + rowId].Value = i;
                    ws.Cells["B" + rowId].Value = item.Fio;
                    ws.Cells["C" + rowId].Value = item.StudentGroup;
                    if (!String.IsNullOrEmpty(item.PracticePlace))
                        ws.Cells["D" + rowId].Value = item.PracticePlace;
                    if (!String.IsNullOrEmpty(item.LecturerPractice))
                        ws.Cells["E" + rowId].Value = item.LecturerPractice;
                    if (!String.IsNullOrEmpty(item.Theme))
                        ws.Cells["F" + rowId].Value = item.Theme;
                    if (!String.IsNullOrEmpty(item.LecturerDiplom))
                        ws.Cells["G" + rowId].Value = item.LecturerDiplom;
                    if (!String.IsNullOrEmpty(item.Note))
                        ws.Cells["H" + rowId].Value = item.Note;


                }
                ws.Cells["A12:A" + rowId].Style.Font.Size = 10;
                ws.Cells["A12:A" + rowId].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;

                ws.Cells["B12:J" + rowId].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;

                ws.Cells["A12:J" + rowId].Style.Font.Name = "Times New Roman";
                ws.Cells["A12:J" + rowId].Style.Font.Size = 12;
                ws.Cells["A12:J" + rowId].Style.WrapText = true;
                ws.Cells["A12:J" + rowId].Style.VerticalAlignment = ExcelVerticalAlignment.Top;


                ws.Cells["A11:H" + rowId].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                ws.Cells["A11:H" + rowId].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                ws.Cells["A11:H" + rowId].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                ws.Cells["A11:H" + rowId].Style.Border.Left.Style = ExcelBorderStyle.Thin;

                //ws.Cells["I11:I" + rowId].Style.Border.Top.Style = ExcelBorderStyle.None;
                //ws.Cells["I11:I" + rowId].Style.Border.Bottom.Style = ExcelBorderStyle.None;

                //Описание нижней части приказа
                rowId += 3;
                int footId = rowId;

                ws.Cells["A" + rowId + ":C" + rowId].Merge = true;
                ws.Cells["A" + rowId].Value = "Перший проректор";
                ws.Cells["A" + rowId].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                ws.Cells["A" + rowId].Style.VerticalAlignment = ExcelVerticalAlignment.Center;

                ws.Cells["F" + rowId].Value = "В.В. Семенець";
                ws.Cells["F" + rowId].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                ws.Cells["F" + rowId].Style.VerticalAlignment = ExcelVerticalAlignment.Bottom;

                rowId += 3;
                ws.Cells["A" + rowId + ":B" + rowId].Merge = true;
                ws.Cells["A" + rowId].Value = "Проект наказу вносить:";

                ws.Cells["E" + rowId].Value = "Узгоджено:";
                ws.Cells["E" + rowId].Style.WrapText = true;

                rowId++;
                ws.Cells["A" + rowId + ":B" + rowId].Merge = true;
                ws.Cells["A" + rowId].Value = "Зав. кафедрою";

                ws.Cells["E" + rowId].Value = "Декан ф-ту";

                rowId++;
                ws.Cells["C" + rowId].Value = "І.Б. Прізвище";
                ws.Cells["H" + rowId].Value = "І.Б. Прізвище";

                rowId++;
                ws.Cells["E" + rowId].Value = "Начальник ВОНП";

                rowId++;
                ws.Cells["H" + rowId].Value = "В.В. Логвін";

                rowId++;
                ws.Cells["E" + rowId].Value = @"Зав. відділом практики ""Центр - Кар'єра""";

                rowId++;
                ws.Cells["H" + rowId].Value = "І.М. Ткаченко";

                ws.Cells["A" + footId + ":J" + rowId].Style.Font.Size = 14;
                ws.Cells["A" + footId + ":J" + rowId].Style.Font.Name = "Times New Roman";

                p.SaveAs(fileInfo);
            }
        }

        private static bool IsNewFile(FileInfo fileInfo, int status)
        {
            if (status == 0 || status == 1)
            {
                //New or Printing status
                if (fileInfo.Exists) fileInfo.Delete();
                return true;
            }
            return false;
        }

        #endregion
    }
}